package com.heima.user.service.impl;

import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.UserService;
import com.heima.user.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult userFollow(UserRelationDto dto) {

        // 1. 入参判空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 2. 查询用户信息
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        // 获取用户id
        Integer userId = user.getId();
        if (userId == null || userId == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        // 3. 判断用户行为
        // 获取用户行为
        Short operation = dto.getOperation();
        // 获取作者
        Integer authorId = dto.getAuthorId();

        if (0 == operation) {

            // 添加关注记录
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION + userId, authorId.toString(), System.currentTimeMillis());

            // 添加粉丝记录
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION + authorId, userId.toString(), System.currentTimeMillis());

        } else {

            // 删除关注记录
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION + userId, authorId.toString());

            // 删除粉丝记录
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION + authorId, userId);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
